/**
 * 
 */
package com.scaffold.commons.config;

import java.io.IOException;
import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author wangjg
 *
 */
public class ZooKeeperOpt implements Watcher {
	private static final Logger log = LoggerFactory.getLogger(ZooKeeperOpt.class);
	private String connectString;
	
	private ZooKeeper zk = null;
	
	private ZooKeeper zk(){
		if(this.zk==null){
			try {
				this.zk = new ZooKeeper(connectString, 60000, this);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return this.zk;
	}
	
	public void create(String path, byte data[]) throws KeeperException, InterruptedException{
		this.zk().create(path, data, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
	}
	
	public List<String> getChildren(String path){
		try {
			return this.zk().getChildren(path, true);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public void setData(String path, byte data[]) throws KeeperException, InterruptedException{
		this.zk().setData(path, data, -1);
	}
	
	public byte[] getData(String path){
		try {
			return this.zk().getData(path, true, null);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public void delete(String path) throws InterruptedException, KeeperException{
		this.zk().delete(path, -1);
	}
	
	public void close() throws InterruptedException{
		this.zk().close();
	}

	@Override
	public void process(WatchedEvent event) {
		log.debug(""+event);
	}

	public String getConnectString() {
		return connectString;
	}

	public void setConnectString(String connectString) {
		this.connectString = connectString;
	}
	
}
